﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace STHPMS1.Common.C_Extension
{
    public static class EnumExt
    {
        public static string EnumToJson(this Type type)
        {
            var stringBuilder = new StringBuilder();
            Array values = Enum.GetValues(type);
            //stringBuilder.Append(string.Format(@"{{ ""{0}"": {{", type.Name));
            stringBuilder.Append("[");

            foreach (Enum e in values)
            {
                int id = Convert.ToInt32(e);
                string text = e.GetEnumDescription();
                stringBuilder.Append("{ 'id':" + id + ",'text':'" + text + "' },");
            }

            stringBuilder.Remove(stringBuilder.Length - 1, 1);
            stringBuilder.Append("]");
            return stringBuilder.ToString();
        }

        public static string GetEnumDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());

            DescriptionAttribute[] attributes =
                (DescriptionAttribute[])fi.GetCustomAttributes(
                typeof(DescriptionAttribute),
                false);

            if (attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }
        /// <summary>
        /// 是枚举类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public static bool IsEnumType(this int? value, Enum e)
        {
            int v = value ?? 0;
            return v == Convert.ToInt32(e);

        }
        public static bool IsEnumType(this int value, Enum e)
        {
            return value == Convert.ToInt32(e);

        }
        /// <summary>
        /// 获取枚举值
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static int GetEnumValue(this Enum e)
        {
            return Convert.ToInt32(e);
        }
        /// <summary>
        /// 获取枚举名称
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string GetEnumName(this Enum e)
        {
            return Enum.GetName(e.GetType(), e);
        }
    }
}
